package com.javatest.springboot3minio.controller;

import com.javatest.springboot3minio.utils.MinioBucketUtil;
import com.javatest.springboot3minio.utils.MinioFileUtil;
import java.util.List;
import javax.validation.constraints.NotBlank;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * Created with IntelliJ IDEA. Description:
 *
 * @author liuzi
 * @since 2024/1/10 13:30
 */
@Validated
@Controller
public class FileManageController {
  private static final Logger LOGGER = LoggerFactory.getLogger(FileManageController.class);

  @GetMapping("/getBucketList")
  public String listBucket(Model model) {
    final List<String> bucketNames = MinioBucketUtil.listBucketNames();
    model.addAttribute("bucketNameList", bucketNames);
    return "main::bucketNameList";
  }

  @ResponseBody
  @PostMapping("/createBucket")
  public String createBucket(
      @NotBlank(message = "bucketName不能为空") @RequestParam(name = "bucketName") String bucketName) {
    final String result = MinioBucketUtil.createBucket(bucketName) ? "创建成功" : "创建失败";
    LOGGER.info("创建bucket[{}],创建结果:{}", bucketName, result);
    return result;
  }

  @ResponseBody
  @PostMapping("/listFilesByBucket")
  public List<String> listFilesByBucket(
      @NotBlank(message = "bucketName不能为空") @RequestParam(name = "bucketName") String bucketName) {
    LOGGER.info("获取[{}]下的文件列表", bucketName);
    return MinioFileUtil.listFileNamesInBucket(bucketName);
  }
}
